package com.netty.handler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import com.netty.collection.EntityContainer;
import com.netty.entity.EntityType;
import com.netty.entity.MethodType;
import com.netty.http.HttpResponseMsg;

import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;

public class BootHandler {
	
	public static HttpResponseMsg doTrans(HttpRequest httpRequest) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, URISyntaxException{
		HttpResponseMsg hrm = new HttpResponseMsg();
		hrm.setResType(HttpResponseMsg.ResType.HTML.getValue());
		hrm.setResCode(HttpResponseMsg.ResCode.OK.getValue());
		FullHttpRequest request = (FullHttpRequest) httpRequest;
		Map<String,Object> params = new HashMap<String,Object>();
		URI uri = new URI(request.uri());
		String path = uri.getPath();
		if(request.method().equals(HttpMethod.GET)){
			System.out.println(uri.getQuery());
			if(uri.getQuery()!=null && !"".equals(uri.getQuery())){
				createGetParamMap(params,uri.getQuery());
			}
		}else if(request.method().equals(HttpMethod.POST)){
			System.out.println(request.content().toString(Charset.forName("UTF-8")));
			createGetParamMap(params,request.content().toString(Charset.forName("UTF-8")));
		}
		
		String className = EntityContainer.getInstance().hashName(path);
		if (className != null) {
			System.out.println("bean： " + className);
			EntityType entityType = EntityContainer.getInstance().get(className);
			String methodName = entityType.hashName(path, className);
			System.out.println("method： " + methodName);
			MethodType methodType = entityType.getFieldMap().get(methodName);
			Method method = methodType.getMethod();
			Object ret = method.invoke(entityType.getObj(), params);
			hrm.setResType(methodType.getDataType());
			hrm.setMessage(ret.toString());
			return hrm;
		}else{
			hrm.setMessage("无知啊");
			hrm.setResCode(HttpResponseMsg.ResCode.INTERNAL_ERROR.getValue());
			return hrm;
		}
		 
	}
	
	public static void createGetParamMap(Map<String,Object> params,String query){
		String[] querys = query.split("&");
		for(int i=0;i<querys.length;i++){
			String paramQuery = querys[i];
			String[] map = paramQuery.split("=",2);
			if(map == null || map.length != 2)continue;
			params.put(map[0], map[1]);
		}
	}
}
